/* eslint-disable */
import axios from 'axios'
import qs from 'qs'
import { Message, MessageBox } from '@cci/cui'
import store from '@/store'
import { getToken, getWebsiteId } from '@/utils/auth'
import { isJSON, createDownloadLink } from '@/utils'

axios.defaults.transformRequest = function(data, headers) {
  if (store.getters.token) {
    headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if (store.getters.websiteId) {
    headers['scope'] = getWebsiteId()
  }
  if (
    headers['Content-Type'] === 'application/x-www-form-urlencoded' &&
    data &&
    Object.prototype.toString.call(data) === '[object Object]'
  ) {
    data = qs.stringify(data)
  }
  return data
}
// 创建axios实例
const axiosObj =
  process.env.NODE_ENV === 'development'
    ? {
        withCredentials: true
        // timeout: 300000 // 请求超时时间
      }
    : {
        baseURL: `${process.env.VUE_APP_API_URL_PREFIX}`,
        withCredentials: true
        // timeout: 300000 // 请求超时时间
      }
const service = axios.create(axiosObj)

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = isJSON(response.data)
      ? JSON.parse(response.data)
      : response.data

    // token 失效
    if (res.code === -2 || res.code === -1) {
      MessageBox({
        type: 'warning',
        title: '警告',
        message: res.message,
        showClose: false
      }).then(() => {
        if (res.url !== undefined) {
          window.location.href = res.url
        }
      })
      return Promise.reject('error')
    } else {
      if (typeof res === 'object') {
        if ('success' in res && !res.success) {
          const msgStr = 'message:'
          const message =
            res.message && res.message.indexOf(msgStr) > -1
              ? res.message.split(msgStr)[1]
              : res.message

          Message({
            type: 'error',
            message: message
          })
          return res
        } else {
          return res
        }
      } else {
        // 针对返回 res 是二进制数据流
        return response
      }
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export function request(_param) {
  const {
    method = 'get',
    // `responseType` 表示服务器响应的数据类型，可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
    responseType = 'json', // 默认的
    headers = {},
    url = '',
    params,
    data,
    ...otherData
  } = _param
  if (!url) {
    return new Promise((resolve, reject) => {
      reject('url is null')
    })
  }
  const _method = method.toLowerCase()

  if (_method === 'get') {
    return axios({
      responseType,
      url,
      headers,
      method,
      params: params || data || otherData
    })
  }

  if (_method === 'post') {
    if (!headers.hasOwnProperty('Content-Type')) {
      headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    if (params && data) {
      return axios({
        responseType,
        url,
        headers,
        method,
        params,
        data
      })
    } else {
      const { start, limit, ...resetData } = otherData
      return axios({
        responseType,
        url,
        headers,
        method,
        params: params || { start, limit },
        data: data || resetData
      })
    }
  }
}
export function download(_param) {
  if (!_param.hasOwnProperty('responseType')) {
    _param.responseType = 'blob'
  }
  return request(_param)
    .then(res => {
      if (res.status === 200 && res.request.readyState === 4) {
        createDownloadLink(res)
      } else {
        Message({
          type: 'error',
          message: '下载失败'
        })
      }
      return res
    })
    .catch(error => {
      console.log(error)
      return error
    })
}
export function upload(_param) {
  const {
    timeout = 300000,
    method = 'POST',
    headers = {
      'Content-Type': 'multipart/form-data'
    },
    url = '',
    params,
    data
  } = _param
  const errmsg = `timeout of ${timeout}ms exceeded`
  return axios({
    timeout,
    url,
    headers,
    method,
    params,
    data
  })
    .then(res => {
      if (res.status === 200 && res.request.readyState === 4) {
        return res
      } else {
        Message({
          type: 'error',
          message: '上传失败'
        })
      }
      return res
    })
    .catch(error => {
      Message({
        type: 'error',
        message: errmsg
      })
      return error
    })
}

export default service
